package com.gzhryc.servlet;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

public class AllowOriginsHelper {

	static AllowOriginsHelper me;

	public static AllowOriginsHelper self() {
		if (me == null) {
			me = new AllowOriginsHelper();
		}
		return me;
	}

	List<String> allowOrigins;

	public AllowOriginsHelper() {
		this.allowOrigins = new ArrayList<String>();
	}
	
	/**
	 * 添加跨域地址
	 * @param address
	 */
	public void addAddress(String address) {
		this.allowOrigins.add(address);
	}
	
	public boolean setAllowOrigins(HttpServletRequest httpRequest,HttpServletResponse httpResponse) {
		// 检查请求，如果为指定域名则设置可以跨域
		String originHeads = httpRequest.getHeader("Origin");
		if (allowOrigins.contains(originHeads) || allowOrigins.contains("all")) {
			httpResponse.setHeader("Access-Control-Allow-Origin", originHeads);
			httpResponse.setHeader("Access-Control-Allow-Methods", "POST,GET,OPTIONS,DELETE,HEAD,PUT,PATCH");
			httpResponse.setHeader("Access-Control-Max-Age", "36000");
			httpResponse.setHeader("Access-Control-Allow-Headers", "Origin, X-Requested-With, Content-Type, Accept,Authorization,authorization");
			httpResponse.setHeader("Access-Control-Allow-Credentials", "true");
			return true;
		}
		return false;
	}
}
